package com.lagou.task.servlet;

import com.lagou.task.model.Admin;
import com.lagou.task.service.AdminService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("获取到的用户名："+username);
        String password = request.getParameter("password");
        System.out.println("获取到的密码："+password);
        // 创建UserService类型的对象去实现数据的校验功能
        AdminService adminService = new AdminService();
        Admin admin = adminService.userLoginService(new Admin(username, password));
        if(null ==admin){
            System.out.println("登录失败");
            request.setAttribute("error","登录失败！");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request,response);
        }else {
            System.out.println("登录成功");
            request.getSession().setAttribute("admin",admin);
            response.sendRedirect("main.jsp");
        }
    }
}
